package com.heyu.cgsd.ui.activity

import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.view.KeyEvent
import android.widget.RadioGroup
import com.heyu.cgsd.R
import com.heyu.cgsd.base.BaseActivity
import com.heyu.cgsd.ui.fragment.HomeFragment
import com.heyu.cgsd.ui.fragment.SettingFragment
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity(), RadioGroup.OnCheckedChangeListener {

    private var homeFragment: HomeFragment? = null
    private var settingFragment: SettingFragment? = null
    private var manager: FragmentManager? = null

    override fun initView() {
        main_table.setOnCheckedChangeListener(this)
        main_tab_1!!.isChecked = true
    }

    override fun getContentView(): Int? {
        return R.layout.activity_main
    }

    override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {
        selectTab(checkedId)
    }

    //进行选中Tab的处理
    private fun selectTab(id: Int) {
        //获取FragmentManager对象
        if (manager == null) {
            manager = supportFragmentManager
        }
        val transaction = manager!!.beginTransaction()
        //先隐藏所有的Fragment
        hideFragments(transaction)
        when (id) {
            R.id.main_tab_1 -> if (homeFragment == null) {
                homeFragment = HomeFragment()
                transaction.add(R.id.main_fragment, homeFragment!!)
            } else {
                transaction.show(homeFragment!!)
            }
            R.id.main_tab_2 -> if (settingFragment == null) {
                settingFragment = SettingFragment()
                transaction.add(R.id.main_fragment, settingFragment!!)
            } else {
                transaction.show(settingFragment!!)
            }
        }
        transaction.commitAllowingStateLoss()
    }

    private fun hideFragments(transaction: FragmentTransaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment!!)
        }
        if (settingFragment != null) {
            transaction.hide(settingFragment!!)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("温馨提示")
                    .setMessage("确认退出吗?")
                    .setCancelable(false) //禁止按下返回false
                    .setCanceledOnTouchOutside(false) //禁止触摸false
                    .addAction("取消") { dialog, _ -> dialog.dismiss() }
                    .addAction("确定") { dialog, _ ->
                        dialog.dismiss()
                        finish()
                    }.show()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}